<template>
    <div style="border: 1px solid #ccc">
      <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode"/>
      <Editor style="height: 500px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated"/>
    </div>
    <el-dialog v-model="dialogVisible" title="html代码编辑" width="80%">
      <HtmlCode v-if="dialogVisible" :info="codeInfo" @updateCode="getCode"/>
    </el-dialog>
</template>
<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { Boot, DomEditor } from '@wangeditor/editor'
import { computed, ref, onMounted, shallowRef, onBeforeUnmount } from 'vue';
import {adornUrl} from '@/utils/index.js'
import {getToken} from '@/utils/auth.js'
import {MyHtmlButton} from "@/utils/wangeToolbar.js"
import { ElDialog } from 'element-plus'
import HtmlCode from "./htmlCode.vue"
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
const editorRef = shallowRef()
const dialogVisible = ref(false)
const codeInfo = ref()
// 内容 HTML
const valueHtml = computed({
    set:(val) =>{
        emit('update:modelValue', val)
    },
    get:() => {
        return props.modelValue
    }
})
const menu1Conf = {
  key: 'html-btn', // 定义 menu key ：要保证唯一、不重复（重要）
  factory() {
    return new MyHtmlButton() // 把 `YourMenuClass` 替换为你菜单的 class
  },
}
Boot.registerMenu(menu1Conf)
const toolbarConfig = {}
const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {} 
}
toolbarConfig.excludeKeys = ["uploadVideo"]
toolbarConfig.insertKeys = {
    index: 0, // 插入的位置，基于当前的 toolbarKeys
    keys: ['html-btn']
}
editorConfig.MENU_CONF['uploadImage'] = {
    server: adornUrl('/base/fund/upload'),
    fieldName: 'file',
    maxFileSize: 5 * 1024 * 1024, // 限制图片大小
    headers: {
        token: getToken()
    },
    customInsert(res, insertFn) {
        // res 即服务端的返回结果
        insertFn(res.fundLogUrl, res.fundLogUrl, res.fundLogUrl)
    },
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()

})

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！

    editor.on('htmlClick', () => { 
      dialogVisible.value = true  
      codeInfo.value = editor.getHtml()
      console.log(editor.getHtml());
    }) 
}
//  获取编辑的代码
const getCode = (event) => {
    console.log(event,'html');
    dialogVisible.value = false
    // valueHtml.value  = event
    editorRef.value.setHtml(event)
}

</script>